<template>
  <view class="login flex-col">
    <!-- header -->
    <view class="header">
      <view class="title"> 欢迎登录！ </view>
    </view>

    <!-- 内容 -->
    <view class="login-form flex-col align-center">
      <tui-form ref="loginRef"></tui-form>

      <!-- logo -->
      <img class="logo" data="" src="./assets/logo.png" alt="" />

      <!-- 账号/密码 -->
      <tui-input
        :borderBottom="false"
        clearable
        v-model="formData.account"
        :labelSize="28"
        :size="28"
        backgroundColor="#F9F9F9"
        maxlength="11"
        label="账号"
        style="width: 100%"
        placeholder="请输入账号/手机号"
      ></tui-input>

      <tui-input
        type="password"
        clearable
        :borderBottom="false"
        v-model="formData.password"
        :marginTop="56"
        :labelSize="28"
        :size="28"
        backgroundColor="#F9F9F9"
        label="密码"
        style="width: 100%"
        placeholder="请输入密码"
      ></tui-input>

      <!--  协议 -->
      <view class="agreement flex-row align-center">
        <checkbox-group @change="agree = !agree">
          <checkbox
            value=""
            class="agreement-checkbox"
            :checked="agree"
            color="#F74E51"
          />
        </checkbox-group>

        <view class="flex-row tip">
          <text class="padding-right-half">登录即同意</text>
          <navigator class="text-orange" url="/pages/cms/xieyi"
            >《{{ app_name }}证券账户免责条款、隐私协议》</navigator
          >

          并使用本机号码登录、未注册{{
            app_name
          }}证券账户的手机号，登录时将自动注册
        </view>
      </view>

      <tui-button
        class="login-btn"
        :loading="submiting"
        :disabled="submiting"
        type="theme"
        @click="submit"
        margin="60rpx 0 0 0"
        >登录</tui-button
      >
      <tui-button
        class="register-btn"
        type="warning"
        plain
        link
        @click="register"
        :loading="submiting"
        :disabled="submiting"
        margin="30rpx 0 0 0"
      >
        <text>注册账号 </text>
        <img class="register-arrow" src="./assets/arrow-right.png" alt="" />
      </tui-button>
    </view>

    <!--  #ifdef APP-PLUS -->
    <view class="flex justify-center pos-b">
      <picker
        mode="selector"
        :range="lines"
        @change="changeLine"
        range-key="name"
      >
        <view
          >线路：{{ lineIndex >= 0 ? lines[lineIndex].name : '腾讯云' }}</view
        >
        <view class="text-gray text-sm text-center">当前版本8.1.2</view>
      </picker>
      <view style="flex: 1; text-align: right" @click="refresh()">
        <!-- <image
					:class="isAnimationDataRefresh ? 'refreshimg' : ''"
					:style="{ width: '70rpx', height: '40rpx' }"
					src="../../static/images/addressRefresh.png"
				></image> -->

        <img
          :class="isAnimationDataRefresh ? 'refreshimg' : ''"
          :style="{ width: '70rpx', height: '40rpx' }"
          src="./assets/logo.png"
          alt=""
        />
      </view>
    </view>
    <tui-picker
      :show="show__1"
      radius
      bold
      :pickerData="lines"
      @hide="hide"
      @change="changeLine"
    >
    </tui-picker>
    <!--  #endif -->
    <tui-loading v-if="submiting" text="服务器连接中..." fixed></tui-loading>

    <tui-modal
      :show="show__2"
      custom
      @cancel="show__2 = false"
      padding="26rpx"
      :maskClosable="false"
      :button="button6"
    >
      <scroll-view scroll-y="true" style="min-height: 60vh; height: 60vh">
        <view
          class="text-center text-nomal margin-top-sm padding-left-sm padding-right-sm"
        >
          <u-parse :content="content"></u-parse>
        </view>
      </scroll-view>
      <view class="flex justify-around">
        <tui-button
          @click="show__2 = false"
          margin="0 30rpx 0 0"
          type="white"
          :plain="false"
          :size="28"
          height="80rpx"
          >不同意</tui-button
        >
        <tui-button
          @click="ssss()"
          margin="0 0 0 30rpx"
          type="theme"
          :size="28"
          height="80rpx"
          >同意</tui-button
        >
      </view>
    </tui-modal>
  </view>
</template>

<script setup>
  import { ref, reactive, getCurrentInstance } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import tui from '@/common/httpRequest';
  import { loginUser } from '@/api/user.js';
  import { useUserStore, useMainStore } from '@/store';

  defineOptions({
    name: 'Login',
  });

  // store
  const userStore = useUserStore();
  const mainStore = useMainStore();

  const apis = [
    'https://zhongxin1224.oss-cn-beijing.aliyuncs.com/zhongxin.json', //阿里云
    'https://zhongxin1224.bj.bcebos.com/zhongxin.json', //百度云
    'https://jiangsu-10.zos.ctyun.cn/bucket-c142/zhongxin.json', //天翼云
    'http://sovvsh4fw.hn-bkt.clouddn.com/app_api/zhongxin.json', //七牛云
  ];

  const app_name = ref('华泰');
  const lineAvailable = ref(false); //线路是否可使用
  const lineIndex = ref(-1);
  const lines = ref([
    {
      name: '',
      value: '',
    },
  ]);
  const agree = ref(false);
  const formData = reactive({
    account: '',
    password: '',
  });
  const submiting = ref(false);
  const isAnimationDataRefresh = ref(false);
  const show__1 = ref(false);
  const show__2 = ref(false);
  const button6 = ref([
    {
      text: '不同意',
      type: 'white',
      plain: true,
    },
    {
      text: '同意',
      plain: false,
    },
  ]);
  const content = ref('');

  // 登录
  const loginRef = ref(); // form 组件示例
  const submit = async () => {
    console.log('tui', tui);
    // #ifdef APP-PLUS
    if (!lineAvailable.value) {
      tuiModal(null, '当前线路不可用,请切换至其他线路', false);
      return;
    }

    // #endif

    console.log('agree.value', agree.value);
    // 同意用户协议
    if (!agree.value) {
      tui.toast('请阅读并同意用户协议');
      return;
    }

    // 校验
    let rules = [
      {
        name: 'account',
        rule: ['required', 'isMobile'],
        msg: ['请输入手机号', '请输入正确的手机号'],
      },
      {
        name: 'password',
        rule: ['required'],
        msg: ['请输入密码'],
      },
    ];

    // 账号密码数据
    let postData = {
      ...formData,
    };

    console.log('postData', postData);

    // 校验账号密码
    let checkRes;

    try {
      checkRes = await loginRef.value.validate(postData, rules);
    } catch (e) {
      //TODO handle the exception
      console.log(e);
      checkRes = e;
    }

    // 账号校验通过
    if (checkRes.isPass) {
      // 开启loading
      submiting.value = true;

      try {
        const res = await loginUser(postData);
        console.log('res', res);

        if (res.code == 1) {
          // 用户信息存入pinia
          userStore.setUser(res.data.userinfo);

          // 登录信息存入本地缓存
          uni.setStorageSync('token', res.data.userinfo.token);
          uni.setStorageSync('account', formData.account);
          uni.setStorageSync('password', formData.password);

          await mainStore.getConfig();
          uni.switchTab({
            url: '/pages/tabbar/index',
          });
        } else {
          tui.toast(res.msg);
        }
      } catch (err) {
        console.error('err', err);
        tui.toast(res.msg);
      } finally {
        submiting.value = false;
      }
    } else {
      tui.toast(checkRes.errorMsg);
    }
  };

  // 登录
  const register = () => {
    uni.navigateTo({
      url: '/pages/login/register',
    });
  };

  // onLoad
  onLoad(() => {
    content.value =
      `<p style="text-align: center; line-height: 2;"><b><span style="font-size: 18px;">温馨提示</span></b></p><p>&nbsp; &nbsp; &nbsp; 欢迎您使用` +
      app_name.value +
      `账户App，为了加强对您个人信息的保护，我们依照最新的法律法规及监管政策要求更新了隐私政策。我们将在充分保障您的知情权且获取您明确授权后收集，使用您的个人信息。</p><p>&nbsp; &nbsp; &nbsp; 请您务必仔细阅读并确认<a style="color: rgb(0, 0, 255);">《` +
      `账户隐私政策条款》</a>和<a style="color: rgb(0, 0, 255);">《` +
      app_name.value +
      `账户服务协议》</a>。我们将严格按照政策内容使用和保护您的个人信息，为您提供更好的服务，感谢您的信任</p>`;

    let token = uni.getStorageSync('token');
    console.log('token', token);

    // token 存在, 则跳转首页
    if (token) {
      uni.switchTab({
        url: '/pages/tabbar/index',
      });
      return;
    }

    // token 不存在
    // #ifdef APP-PLUS
    let index = uni.getStorageSync('curr_api_line_index') || 0;
    console.log('index', index);

    // 清理本地缓存
    uni.clearStorage();
    if (!index) {
      this.getBase(0);
    } else {
      this.getBase(index);
    }
    // #endif

    let ssss = uni.getStorageSync('ssss');
    console.log('ssss', ssss);
    // console.log(ssss)
    if (ssss) {
      this.show__2 = false;
    }
  });
</script>

<style lang="scss" src="./css/index.scss" scoped></style>
